package dao.impl;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import pojo.Comment;
import pojo.Complaint;
import pojo.Order;
import dao.OrderDao;

/**
 * Created by CHENCO7 on 8/12/2017.
 */
@Repository
public class OrderDaoImpl implements OrderDao {
    @PersistenceContext(name="un")
    private EntityManager manager;

    @Override
    public Order addOrder(Order order) {
        manager.persist(order);
        return order;
    }

    @Override
    public Order loadOrder(String id) {
        return manager.find(Order.class, id);
    }

    @Override
    public Order updateOrder(Order order) {
        Order o = manager.find(Order.class, order.getId());
        manager.persist(o);
        return o;
    }

    @Override
    public List<Order> getOrderListByCustomerId(String id) {
        String jpql = "select distinct o from Order o INNER JOIN fetch o.orderItemList where o.customer.id =:id";
        List<Order> orderList = manager.createQuery(jpql).setParameter("id", id).getResultList();
        return orderList;
    }

	@Override
	public Order addComment(String comment, String starCount, String o_id) {
		Order order = (Order)manager.find(Order.class, o_id);
		order.setStar(Integer.parseInt(starCount));
		Comment comment1 = new Comment(comment, new Date());
		order.getComment().add(comment1);
		return order;
	}

	@Override
	public Order addComplain(String complain, String o_id) {
		Order order = (Order)manager.find(Order.class, o_id);
		Complaint complaint1 = new Complaint(complain, new Date());
		order.setComplaint(complaint1);
		return order;
	}

    @Override
    public Order loadOrderItem(String orderId) {
        Query query = manager.createQuery("select o from Order o INNER JOIN fetch o.orderItemList where o.id =:orderId");
        Order order = (Order) query.setParameter("orderId", orderId).getSingleResult();
        return order;
    }

}
